<script setup>
import MyBreadcrumb from '../../../components/MyBreadcrumb/index.vue';
import { useStore } from 'vuex';
import { useRouter, useRoute, onBeforeRouteUpdate } from 'vue-router';
import * as goodsApi from '../../../api/goods.js';
import { watchEffect } from 'vue';

const route = useRoute();
const store = useStore();
const router = useRouter();
const currentPage = ref(1);
const index = ref(1);
const iconColor = ref(true);
const saleIndex = ref(null);
const checked1 = ref(false);
const checked2 = ref(false);
let currentSortField = null;
const data = ref(null);
// 记录
let observer = null;
let lastObserver = null;

// 获取三级页面
// store.dispatch('second/updateSubCategoryList', route.params.id);

watchEffect(() => {
  store.dispatch('second/updateSubCategoryList', route.params.id);
});
const subCategoryList = computed(() => store.state.second.subCategoryList);

// 获取三级页面的商品列表
function init(to) {
  store.dispatch('goods/updateSubCategoryGoodsList', {
    categoryId: to.params.id,
    page: currentPage.value,
    pageSize: 20,
  });
}
init(route);
const subCategoryGoodsList = computed(() => store.state.goods.subCategoryGoodsList);
console.log(subCategoryGoodsList.value, '333');

// 懒加载
// 路由id变化时, 重新请求
onBeforeRouteUpdate(init);
const hasNext = computed(() => subCategoryGoodsList.value.pages > currentPage.value);
watch(subCategoryGoodsList, async () => {
  if (!hasNext.value) {
    return;
  }
  await nextTick();
  // 取消上一轮的观察

  if (observer) {
    observer.unobserve(lastObserver);
  }

  // 当clothes滚动到视野中时, dispatch
  observer = new IntersectionObserver(
    (entries) => {
      if (entries[0].isIntersecting) {
        // 应该自己写的内容

        store.dispatch('goods/updateSubCategoryGoodsList', {
          page: ++currentPage.value,
          pageSize: 20,
          categoryId: route.params.id,
        });
      }
    },
    {
      root: null,
      rootMargin: '0px',
      threshold: 0.5,
    },
  );

  lastObserver = document.querySelector('.item:nth-last-child(5)');
  // console.log(lastObserver);
  // 启动观察clothes.value是否进入视野
  observer.observe(lastObserver);
});

// 面包屑
const breadcrumb = computed(() => [
  { path: '/home', breadcrumbName: '首页' },
  { path: '/category/' + subCategoryList.value.parentId, breadcrumbName: subCategoryList.value.parentName },
  { path: '/category/sub/' + route.params.id, breadcrumbName: subCategoryList.value.name },
]);

// 筛选条件
const state = ref([]);
// 监听请求数据
watch(subCategoryList, () => {
  state.value = subCategoryList.value.saleProperties.map((s) => ({
    groupName: s.name,
    propertyName: null,
  }),
  );
});

// 点击筛选条件
async function onCondition(name, i) {
  state.value[i].propertyName = name;
  store.commit('goods/RESET_SUB_CATEGORY_GOODS_LIST', {
    items: [],
    page: 1,
    pageSize: 10,
    pages: 1,
    counts: 0,
  });
  store.dispatch('goods/updateSubCategoryGoodsList', {
    categoryId: route.params.id,
    page: currentPage.value,
    pageSize: 20,
    attrs: state.value.filter((d) => d.propertyName !== null),
    ...data.value,
  });
}
// 点击全部
function onAll(i) {
  state.value[i].propertyName = null;
  store.commit('goods/RESET_SUB_CATEGORY_GOODS_LIST', {
    items: [],
    page: 1,
    pageSize: 10,
    pages: 1,
    counts: 0,
  });
  store.dispatch('goods/updateSubCategoryGoodsList', {
    categoryId: route.params.id,
    page: 1,
    pageSize: 20,
    attrs: state.value.filter((d) => d.propertyName !== null),
    ...data.value,
  });
}


// 点击按钮)
async function onBtn(n, sortField) {
  data.value = {
    categoryId: route.params.id,
    inventory: checked1.value,
    onlyDiscount: checked2.value,
    page: 1,
    pageSize: 20,
    sortField,
    attrs: state.value,
    sortMethod: null,
  };
  index.value = n;
  currentSortField = sortField;
  if (n === 5) {
    sortMethod = iconColor.value ? 'asc' : 'desc';
    iconColor.value = !iconColor.value;
    await store.commit('goods/RESET_SUB_CATEGORY_GOODS_LIST');
    data.value = {
      ...data.value,
      sortMethod: iconColor.value ? 'asc' : 'desc',
    };
    store.dispatch('goods/updateSubCategoryGoodsList', {
      ...data.value,
    });
  } else {
    store.commit('goods/RESET_SUB_CATEGORY_GOODS_LIST', {
      items: [],
      page: 1,
      pageSize: 10,
      pages: 1,
      counts: 0,
    });
    store.dispatch('goods/updateSubCategoryGoodsList', {
      ...data.value,
    });
  }
}
// 点击多选框
async function onCheckbox() {
  store.commit('goods/RESET_SUB_CATEGORY_GOODS_LIST', {
    items: [],
    page: 1,
    pageSize: 10,
    pages: 1,
    counts: 0,
  });
  store.dispatch('goods/updateSubCategoryGoodsList', {
    categoryId: route.params.id,
    inventory: checked1.value,
    onlyDiscount: checked2.value,
    page: 1,
    pageSize: 20,
    sortField: currentSortField,
    sortMethod: null,
  });
}

// 去详情页
function goDetail(id) {
  router.push({
    path: `/product/${id}`,
  });
}
</script>

<template>
  <div class="sub-category-container">
    <my-breadcrumb :breadcrumb="breadcrumb"/>
    <div class="sub-category-top-container">
      <div class="brands">
        <span>品牌:</span>
        <span
          :class="{
            active: true
          }"
        >
          全部
        </span>
        <div>
          <span
            v-for="item in subCategoryList.brands"
            :key="item.id"
            @click="onCondition(item.id)"
          >
            {{ item.name }}
          </span>
        </div>
      </div>
      <div
        class="saleProperties"
        v-for="(item, i) in subCategoryList.saleProperties"
        :key="item.id"
      >
        <span>{{ item.name }}:</span>
        <span
          :class="{
            active: !state[i]?.propertyName
          }"
          @click="onAll(i)"
        >
          全部
        </span>
        <div>
          <span
            v-for="str in item.properties"
            :key="str.id"
            :class="{
              active: state[i]?.propertyName === str.name
            }"
            @click="onCondition(str.name, i)"
          >
            {{ str.name }}
          </span>
        </div>
      </div>
    </div>
    <div class="sub-category-main-container">
      <div class="sub-category-header-box">
        <div class="btn-warp">
          <button
            :class="{
              btn: true,
              ss: index === 1,
            }"
            @click="onBtn(1, null)"
          >
            默认排序
          </button>
          <button
            :class="{
              btn: true,
              ss: index === 2,
            }"
            @click="onBtn(2, 'publishTime')"
          >
            最新商品
          </button>
          <button
            :class="{
              btn: true,
              ss: index === 3
            }"
            @click="onBtn(3, 'orderNum')"
          >
            最高人气
          </button>
          <button
            :class="{
              btn: true,
              ss: index === 4
            }"
            @click="onBtn(4, 'evaluateNum')"
          >
            评论最多
          </button>
          <button
            :class="{
              btn: true,
              btn1: true,
            }"
            @click="onBtn(5, 'price')"
          >
            价格排序
            <span class="btn-icon">
              <el-icon
                :class="{
                  icon: true,
                  icons: index === 5 && iconColor,
                }"
              >
                <CaretTop />
              </el-icon>
              <el-icon
                :class="{
                  icon: true,
                  icons: index === 5 && !iconColor,
                }"
              >
                <CaretBottom />
              </el-icon>
            </span>
          </button>
        </div>
        <div>
          <el-checkbox
            label="仅显示有货商品"
            size="large"
            v-model="checked1"
            @change="onCheckbox"
          />
          <el-checkbox
            label="仅显示特惠商品"
            size="large"
            v-model="checked2"
            @change="onCheckbox"
          />
        </div>
      </div>
      <div class="sub-category-main-box">
        <div
          class="item"
          v-for="str in subCategoryGoodsList.items"
          :key="str.id"
          @click="goDetail(str.id)"
        >
          <div class="goods-img-warp">
            <img :src="str.picture" alt="">
          </div>
          <div class="goods-name">{{ str.name }}</div>
          <div class="goods-desc">{{ str.desc }}</div>
          <div class="goods-price">¥{{ str.price }}</div>
        </div>
      </div>
      <div class="sub-category-foot-box" v-if="!hasNext">
        <el-empty description=" " />
        <div>亲，没有更多了</div>
      </div>
    </div>

  </div>
</template>

<style scope lang="scss">
@import '@/assets/style/common.scss';
.active {
  color: #5bb79c;
}

.sub-category-container {
  width: 100%;
  background-color: #f5f5f5;
  min-width: 1240px;
  padding: 0 16px;

  .sub-category-top-container {
    width: 1240px;
    margin: 0 auto;
    padding: 20px;
    background-color: #fff;
    font-size: 14px;
    // margin-top: 30px;

    .brands {
      display: flex;
      align-items: center;
      margin-bottom: 20px;

      span {
        margin-right: 20px;
      }

      >span:nth-child(1) {
        color: #989a99;
      }
      span:nth-child(2):hover {
        color: #5bb79c;
        cursor: pointer;
      }

      div {
        flex: 1;

        span {
          &:hover {
            color: #5bb79c;
            cursor: pointer;
          }
        }
      }
    }

    .saleProperties {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 20px;


      span {
        margin-right: 20px;
      }
      >span:nth-child(1) {
        color: #989a99;
      }
      span:nth-child(2):hover {
        color: #5bb79c;
        cursor: pointer;
      }
      div {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
        // margin: 30px 0;

        span {
          display: inline-block;
          @include hide(1);
          width: 100px;
          height: 20px;
          margin-bottom: 20px;

          &:hover {
            color: #5bb79c;
            cursor: pointer;
          }
        }
      }

    }
  }
  .sub-category-main-container {
    width: 1240px;
    margin: 30px auto;
    background-color: #fff;

    .sub-category-header-box {
      width: 100%;
      display: flex;
      justify-content: space-between;
      padding: 16px;
      align-items: center;

      .btn-warp {
        display: flex;
        .btn {
          margin-right: 8px;
          padding: 0 16px;
          height: 35px;
          border: 1px solid #e5e5e5;
          background-color: #fff;
          color: #989a99;
          font-size: 14px;

          &:hover {
            cursor: pointer;
          }

          .btn-icon {
            display: inline-flex;
            flex-direction: column;
            // justify-content: center;

            .icon {
              padding: 0;
              margin: 0;
              font-size: 12px;
              vertical-align: middle;
            }
          }
        }
        .btn1 {
            display: flex;
            align-items: center;
          }
        .ss {
          background-color: #5bb79c;
          color: #fff;
        }
        .icons {
          color: #5bb79c;
        }
      }
    }
    .sub-category-main-box {
      display: flex;
      width: 100%;
      flex-wrap: wrap;
      // padding-left: 30px;
      // justify-content: space-around;

      .item {
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 220px;
        height: 300px;
        padding: 20px 30px;
        text-align: center;
        justify-content: center;
        transition: all 0.5s;
        margin: 0 14px;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 0 10px #ccc;
        }

        .goods-img-warp{
          width: 160px;
          height: 160px;

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }
        .goods-name {
          @include hide(1);
          margin-top: 8px;

        }
        .goods-desc {
          @include hide(1);
          font-size: 14px;
          color: #999999;
          margin: 8px 0;
        }

        .goods-price {
          font-size: 18px;
          color: #bf4e49;
        }
      }
    }
    .sub-category-foot-box{
      width: 100%;
      height: 200px;
      background-color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
      margin: 30px 0;

      div {
        margin-left: 16px;
        font-size: 14px;
        color: #989a99;

      }
    }
  }

}
</style>
